package com.nuc.kl.base;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional//对子类有效，对父类无效
@SuppressWarnings("unchecked")
public abstract class DaoSupportImpl<T> implements DaoSupport<T> {

	@Resource
	private SessionFactory sessionFactory;
	private Class<T> clazz;
	
	public DaoSupportImpl(){
		//使用反射技术得到T的真实类型
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();//获取当前new的对象的泛型的父类类型
		this.clazz = (Class<T>) pt.getActualTypeArguments()[0];//获取 第一个类型参数的真实类型
		System.out.println("clazz -->" + clazz);
	}

	/**
	 * 获取当前可用的Session
	 * 
	 * @return
	 */
	protected Session getSession() {

		return sessionFactory.getCurrentSession();

	}

	public void save(T entity) {

		getSession().save(entity);
	}

	public void delete(Long id) {

		Object obj = getById(id);
		if (obj != null) {
			getSession().delete(obj);
		}
	}

	public T getById(Long id) {
		
		if(id == null){
			return null;
		}else{
			return (T) getSession().get(clazz, id);
		}
		
	}

	public List<T> findAll() {
		return getSession().createQuery(//
				"FROM " + clazz.getSimpleName())//
				.list();
	}

	public List<T> getByIds(Long[] ids) {
		if(ids == null || ids.length == 0 ){
			return Collections.EMPTY_LIST;
		}else{
			return getSession().createQuery(//
					"FROM "+ clazz.getSimpleName() +" WHERE  id IN (:ids)")//
					.setParameterList("ids", ids)//
					.list();
		}
	}

	public void update(T entity) {
		getSession().update(entity);

	}
	
	public Long count(T entity){
		return  (Long) getSession().createQuery(//
				"SELECT COUNT(*) FROM "+ clazz.getSimpleName())//
				.uniqueResult();
	}

	public List<T> findAllPage(int start,int number){
		
		return getSession().createQuery(//
				"FROM " + clazz.getSimpleName())//
				.setFirstResult(start)//
				.setMaxResults(number)//
				.list();
		
	}
	
	public List<T> findBySQL(String sql){
	
		return getSession().createQuery(sql).list();
		
	}
	
}
